package com.example.demo.controller;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisAnnController {

    /**
     * cache添加缓存与获取
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/ann-get")
    @Cacheable(value = "spring.cache",key = "#username+'-'+#password")    //注解缓存(然后下面获取)
    public String get(String username,String password) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return null;
        }
        System.out.println("执行了 get 方法");
        return "username= "+username +" |password= " +password;
    }

    /**
     * 更新缓存
     *
     * @param name
     * @param pnumber
     * @return
     */
    @RequestMapping("/put")
    @CachePut(value = "spring.cache", key = "#name+'-'+#pnumber")
    public String put(String name, String pnumber) {
        if (!StringUtils.hasLength(name) || !StringUtils.hasLength(pnumber)) {
            return null;
        }
        System.out.println("执行了 put 方法");
        return "[name=" + name + " <-> pnumber=" + pnumber + "]";
    }

    /**
     * 缓存删除
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/del")
    @CacheEvict(value = "spring.cache",key = "#username+'-'+#password")
    public String del(String username,String password) {
        System.out.println("执行了缓存删除");
        return "删除成功";
    }
}
